package com.sunday.aomi.ui.product;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.sunday.common.adapter.CommonAdapter;
import com.sunday.common.adapter.RecylerViewHolder;
import com.sunday.common.base.BaseFragment;
import com.sunday.common.event.EventBus;
import com.sunday.common.imageselector.bean.Image;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.PixUtils;
import com.sunday.common.utils.SpannalbeStringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.aomi.R;
import com.sunday.aomi.event.UpdateProductList;
import com.sunday.member.entity.Member;
import com.sunday.member.entity.product.Product;
import com.sunday.member.entity.product.ProductDetail;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;


import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by 刘涛 on 2017/5/23.
 */

public class ProductListFragment extends BaseFragment {


    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    private CommonAdapter<ProductDetail> adapter;
    private List<ProductDetail> dataSet = new ArrayList<>(6);
    private final int PRO_TYPE = 3;//采购商品
    private String name = "", sort = "", order = "";
    private int catId;

    public static ProductListFragment newInstance(String queyName, int catId, String sortStr1, String sortStr2) {
        ProductListFragment fragment = new ProductListFragment();
        Bundle bundle = new Bundle();
        bundle.putString("name", queyName);
        bundle.putInt("categoryId", catId);
        bundle.putString("sort", sortStr1);
        bundle.putString("order", sortStr2);
        fragment.setArguments(bundle);
        return fragment;
    }

    public void setQueryName(String query) {
        name = query;
    }

   public void onEvent(UpdateProductList updateProductList){
       pagNo=1;
       getData();
   }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_product_list, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        EventBus.getDefault().register(this);
        initParams();
        initRecylerView();
        getData();
    }

    private void initParams() {
        if (getArguments() != null) {
            name = getArguments().getString("name");
            catId = getArguments().getInt("categoryId");
            sort = getArguments().getString("sort");
            order = getArguments().getString("order");
        }
    }

    private LinearLayoutManager layoutManager;
    private int lastVisibleItem;
    private boolean isCanloadMore;
    private int pagNo = 1;
    private int pageSize = 10;

    private void initRecylerView() {
        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        adapter = new CommonAdapter<ProductDetail>(mContext, R.layout.layout_index_list, dataSet) {
            @Override
            public void convert(RecylerViewHolder holder, ProductDetail product) {
                bind(holder, product);
            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pagNo=1;
                getData();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pagNo = 1;
                getData();
            }
        });
    }

    private void bind(RecylerViewHolder holder, final ProductDetail product) {
        ImageView imageView = holder.getView(R.id.product_img);
        if (!TextUtils.isEmpty(product.getImage())) {
            Picasso.with(mContext)
                    .load(product.getImage())
                    .error(R.mipmap.ic_default)
                    .resize(150, 150).into(imageView);
        }
        ((TextView) holder.getView(R.id.product_title)).setText(product.getName());
        ((TextView) holder.getView(R.id.price_now)).setText(SpannalbeStringUtils.setTextSizePx("批发价：￥", PixUtils.sp2px(mContext, 12)));
        ((TextView) holder.getView(R.id.price_now)).append(SpannalbeStringUtils.setTextSizePx(
                String.valueOf(product.getPrice().setScale(2, RoundingMode.HALF_UP)), PixUtils.sp2px(mContext, 15)));

        ((TextView) holder.getView(R.id.price_old)).setText(String.format("￥%s", product.getMarketPrice().setScale(2, RoundingMode.HALF_UP)));
        ((TextView) holder.getView(R.id.price_old)).getPaint().setFlags(Paint.ANTI_ALIAS_FLAG | Paint.STRIKE_THRU_TEXT_FLAG);
        holder.setOnClickListener(R.id.total_layout, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(mContext, ProductDetailActivity.class);
                intent.putExtra("productId", product.getId());
                startActivity(intent);
            }
        });

    }

    private void getData() {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"name", "categoryId", "type", "pageSize", "pageNumber", "sort", "order", "nonce"};
        String[] str2 = new String[]{name, catId != 0 ? String.valueOf(catId) : "", String.valueOf(PRO_TYPE), String.valueOf(pageSize),
                String.valueOf(pagNo), sort, order, nonce};
        Call<ResultDO<List<ProductDetail>>> call = MemberClient.getApiAdapter().getProductList(name, catId != 0 ? catId : null, PRO_TYPE, null,
                pageSize, pagNo, sort, order, nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<List<ProductDetail>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<ProductDetail>>> call, Response<ResultDO<List<ProductDetail>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                ptrFrame.refreshComplete();
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    if (pagNo == 1) {
                        dataSet.clear();
                    }
                    dataSet.addAll(response.body().getResult());
                    if (response.body().getResult().size() == 10) {
                        pagNo++;
                        isCanloadMore = true;
                    } else {
                        isCanloadMore = false;
                    }
                    if (dataSet.size() > 0) {
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    } else {
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<ProductDetail>>> call, Throwable t) {
                ptrFrame.refreshComplete();
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
